<?php

namespace catchAdmin\apipatient\service;

use app\common\model\DiseasePatientTask;
use app\common\model\DiseasePatientTaskDetail;
use think\facade\Cache;
use catcher\exceptions\FailedException;
use app\common\model\PropagandaEducation as peModel;
use app\common\model\PropagandaEducationHistory as pehModel;

class EdService
{
    /**
     * 在院宣教签名
     * @param array $data 请求参数数组
     * @param string $id 推送宣教主键
     * @param int $type 推送宣教类型
     * @param string $sign 签名信息
     * @return bool
     */
    public function inEdSign(array $data=[]): bool
    {
        if($data['type'] <> 1)
        {
            throw new FailedException("不是在院宣教类型，不可签名");
        }
        $signData['sign'] = $data['sign'];
        return (new pehModel())->saveData($data['id'], $signData);
    }

    /**
     * 我的宣教详情
     * @param string $id 我的宣教id
     * @param int $type 宣教类型
     * @param string $ed_id 宣教id
     * @return array
     */
    public function EdDetail(string $id, int $type, string $ed_id): array
	{

        $edinfo = (new peModel())->where('id', $ed_id)->find();

        if (!isset($edinfo) || empty($edinfo))
        {
            throw new FailedException("宣教信息不存在");
        }
        
        //获取我的宣教-住院宣教签名
        $history = (new pehModel())->getOneData(['id' => $id, 'type' => $type], 'sign,isview,batch_no');
        $data = $edinfo->toArray();
        $data['sign'] = '';

        if (isset($history) && !empty($history))
        {
            $data['sign'] = $history['sign'];
        }

        //浏览量+1
        Cache::store('redis')->incr('my_ed:'.$id);


        //获取当前浏览量
        $hits = Cache::store('redis')->get('my_ed:'.$id);

        //判断宣教是否已读
        if ($history['isview'] == 0) {

            //判断是否是随访路径推宣教
            if (!isset($history['batch_no'])) {
                (new DiseasePatientTaskDetail())->modifyStatus($id);
            }
            $upHistoryData['isview']    = 1;//标记已读
            $upHistoryData['read_time'] = date("Y-m-d H:i:s");//阅读时间
            $upHistoryData['read_ymd']  = date("Y-m-d");//阅读年月日
        }

        //阅读量
        $upHistoryData['hits'] = $hits;

        //更新字段
        (new pehModel())->saveData($id, $upHistoryData);

        return $data;
	}
}